import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Picker, ImageUploader, TextArea, Collapse } from 'antd-mobile';
import { AddOutline, DownOutline, UpOutline } from 'antd-mobile-icons';
import styles from './index.module.less';
import HeaderNav from "@/components/header-nav"
import { useSearchParams } from 'react-router-dom';
import { showErrorToast, showSuccessToast } from '@/utils/customToast';
const { postCreateRole, postEditRole, getRoleDetails } = $globalServicer('chat')
import { handleImageUpload } from '@/utils/upload';
import { genderColumns, raceColumns, world_categoryColumns, era_backgroundColumns, ROLE_DESCRIPTION_FIELDS } from '@/utils/constant';
import TagSelector from '@/components/TagSelector';
import { defaultUserCover } from '@/utils/config';
const RoleInfoForm = () => {
  const [form] = Form.useForm();
  const [params] = useSearchParams();
  const [roleInfo, setRoleInfo] = useState(null)
  const customNavigate = $globalNavigate()
  const type = params.get('type');
  const tabType = params.get('tabType');
  const id = params.get('id');
  const [submitting, setSubmitting] = useState(false);
  const [genderVisible, setGenderVisible] = useState(false);
  const [visible, setVisible] = useState(false);
  const [eraBackgroundVisible, setEraBackgroundVisible] = useState(false);
  const [worldTypeVisible, setWorldTypeVisible] = useState(false);
  const [isRequired, setIsRequired] = useState(true)
  const [activeKey, setActiveKey] = useState('1')
  const handleAddOption = (option) => {
    console.log("🚀 ~ handleAddOption ~ option:", option)
  }
  
  useEffect(() => {
    if (type === 'edit' && id) {
      getRoleDetails(id).then(res => {
        setRoleInfo(res);
        form.setFieldsValue({
          cover: [
            {
              url: res.cover,
              path: res.cover
            }
          ],
          ...res.description,
          persona_name: res.persona_name,
          remarks: res.remarks,
        })
      })
    } else {
      form.setFieldsValue({
        cover: [
          {
            url: defaultUserCover,
            path: defaultUserCover
          }
        ]
      })
    }
  }, [])
  const onFinish = (values) => {
    console.log('Form values:', values);
    if (submitting) return;
    
    if (!values.gender || !values.race) {
      showErrorToast('请填写必填项');
      return;
    }

    let resultData = {
      cover: values.cover[0].url,
      persona_name: values.persona_name,
      description: {
        gender: values?.gender[0],
        age: values.age,
        race: values?.race[0],
        appearance: values.appearance,
        background: values.background,
        experience: values.experience,
        relationships: values.relationships,
        abilities: values.abilities,
        custom_content: values.custom_content,
      },
      remarks: values.remarks,
    }
    try {
      setSubmitting(true);
      if (type === 'edit' && id) {
        console.log(`------resultData`, resultData)
        resultData.id = id
        postEditRole(resultData).then(res => {
          console.log("🚀 ~ onFinish ~ res:", res)
          customNavigate(`/chatlist?tabType=${tabType}`)
          showSuccessToast('修改成功')
        })
      } else {
        postCreateRole(resultData).then(res => {
          console.log("🚀 ~ onFinish ~ res:", res)
          customNavigate(`/chatlist?tabType=${tabType}`)
          showSuccessToast('创建成功')
        })
      }
    } catch (error) {
      showErrorToast('提交失败，请重试');
    } finally {
      setSubmitting(false);
    }
  };
  return (
    <div className={styles.formContainer}>
      <div className="header">
        <HeaderNav backArrow={true}
          onBack={() => {
            customNavigate(`/chatlist?tabType=${tabType}`)
          }}
          title={type === 'add' ? '创建我的角色' : '编辑我的角色'}
        ></HeaderNav>
      </div>
      <Form
        form={form}
        onFinish={onFinish}
        footer={
          <div className={styles.footer}>
            <Button className={styles.submitButton}
              type='submit'
              loading={submitting}
              disabled={submitting}
            >{submitting ? '提交中...' : '完成'}</Button>
          </div>
        }
      >
        <Form.Item name="cover" label="头像" className={styles.imageItem} required={isRequired} rules={[{ required: isRequired, message: '头像不能为空' }]}>
          <ImageUploader className={styles.uploadWrapper}
            upload={handleImageUpload}
            maxCount={1}
            onDelete={() => {
              return { beforeDelete: () => true };
            }} />
        </Form.Item>
        <Form.Item 
          name="persona_name" 
          label="名称" 
          help="字数上限10"
          required={isRequired} rules={[{ required: isRequired, message: '名称不能为空' }]}>
          <Input placeholder="请输入名称" maxLength={10} />
        </Form.Item>
        <TagSelector
          name="gender"
          label="性别"
          required={isRequired}
          rules={[{ required: isRequired, message: '性别不能为空' }]}
            options={genderColumns}
            multiple={false}
            maxCount={20}
            help='字数上限20'
            onAddOption={handleAddOption}
        />
        <Form.Item name="age" label="年龄" help='字数上限10' required={isRequired} rules={[{ required: isRequired, message: '年龄不能为空' }]}>
          <Input placeholder="请输入年龄" maxLength={10}/>
        </Form.Item>
        <TagSelector
          name="race"
          label="种族"
          required={isRequired}
          rules={[{ required: isRequired, message: '种族不能为空' }]}
            options={raceColumns}
            multiple={false}
            maxCount={20}
            help='字数上限20'
            onAddOption={handleAddOption}
        />
        <Collapse
          activeKey={activeKey}
          onChange={(activeKey) => {
            setActiveKey(activeKey)
          }}
        >
          <Collapse.Panel key='1'
            title={activeKey?.indexOf('1') ? '展开' : '收起'}
            className={styles.collapsePanelWrapper}>
            <Form.Item name="appearance" label="外貌衣着" help='字数上限100'>
              <Input placeholder="输入外貌衣着（字数上限100）" maxLength={100} />
            </Form.Item>
            <Form.Item name="background" label="人物背景" help='字数上限100'>
              <Input placeholder="输入人物背景（字数上限100）" maxLength={100} />
            </Form.Item>
            <Form.Item name="experience" label="人物经历" help='字数上限100'>
              <Input placeholder="输入人物经历（字数上限100）" maxLength={100} />
            </Form.Item>
            <Form.Item name="relationships" label="人际关系" help='字数上限100'>
              <Input placeholder="输入人际关系（字数上限100）" maxLength={100} />
            </Form.Item>
            <Form.Item name="abilities" label="能力设定" help='字数上限100'>
              <Input placeholder="输入能力设定（字数上限100）" maxLength={100} />
            </Form.Item>
            <Form.Item name="custom_content" label="自定义内容" help='字数上限200'>
              <Input placeholder="输入自定义内容（字数上限200）" maxLength={200} />
            </Form.Item>
            <Form.Item name="remarks" label="备注" help="字数上限20">
              <Input placeholder="" maxLength={20} />
            </Form.Item>
          </Collapse.Panel>
        </Collapse>
      </Form>
      <div className={styles.bottomWrapper}></div>
      <Picker
        columns={genderColumns}
        visible={genderVisible}
        onClose={() => {
          setGenderVisible(false)
        }}
        value={[form.getFieldValue('gender')]}
        onConfirm={v => {
          form.setFieldsValue({
            gender: v[0]
          })
          setGenderVisible(false)
        }}
      />
      <Picker
        columns={raceColumns}
        visible={visible}
        onClose={() => {
          setVisible(false)
        }}
        value={[form.getFieldValue('race')]}
        onConfirm={v => {
          form.setFieldsValue({
            race: v[0]
          })
          setVisible(false)
        }}
      />
      <Picker
        columns={era_backgroundColumns}
        visible={eraBackgroundVisible}
        onClose={() => {
          setEraBackgroundVisible(false)
        }}
        value={[form.getFieldValue('world_era')]}
        onConfirm={v => {
          form.setFieldsValue({
            world_era: v[0]
          })
          setEraBackgroundVisible(false)
        }}
      />
      <Picker
        columns={world_categoryColumns}
        visible={worldTypeVisible}
        onClose={() => {
          setWorldTypeVisible(false)
        }}
        value={[form.getFieldValue('world_category')]}
        onConfirm={v => {
          form.setFieldsValue({
            world_category: v[0]
          })
          setWorldTypeVisible(false)
        }}
      />
    </div>
  );
};

export default RoleInfoForm;